export default {
    get(url: string, data: any = {}, headers: object = {}, queryParam = false, success?: (res: string) => void, fail?: () => void) {
        this._request(url, data, "GET", headers, queryParam, success, fail);
    },

    post(url: string, data: any = {}, headers: object = {}, queryParam = false, success?: (res: string) => void, fail?: () => void) {
        this._request(url, data, "POST", headers, queryParam, success, fail);
    },

    _request(url: string, data: any, method = 'GET', headers: any, queryParam = false, success?: (res: string) => void, fail?: () => void) {
        if (queryParam) {
            let cha = '?';
            for (const key in data) {
                if (data.hasOwnProperty(key)) {
                    url += cha;
                    if (cha == '?') {
                        cha = '&';
                    }
                    const element = data[key];
                    url = url + key + '=' + element;
                }
            }
            data = null;
        }

        let xhr = new XMLHttpRequest();
        let pending = true;
        xhr.onerror = () => {
            if (pending && fail) {
                pending = false;
                fail();
            }
        };
        xhr.ontimeout = () => {
            if (pending && fail) {
                pending = false;
                fail();
            }
        }
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 400) {
                    pending = false;
                    success && success(xhr.responseText);
                } else {
                    if (pending && fail) {
                        pending = false;
                        fail();
                    }
                }
            } else {

            }
        }
        xhr.open(method, url, true);
        for (const key of Object.keys(headers)) {
            const val = headers[key];
            xhr.setRequestHeader(key, val);
        }
        xhr.send(JSON.stringify(data));
    }
}